<template>
  <div class="flex h-full">
    <div class="w-85 h-full p-4 flex-shrink-0 border-r flex flex-col border-gray-200 overflow-y-auto">
      <a-input class="mb-4" v-model:value.trim="state.searchName" placeholder="请输入搜索关键字" allow-clear @change="getFolderTree">
        <template #suffix v-if="!state.searchName">
          <SearchOutlined style="color: #999" />
        </template>
      </a-input>
      <a-tree
        v-if="state.treeData.length > 0"
        v-model:selectedKeys="state.selectedKeys"
        class="tree-warpper"
        :block-node="true"
        :tree-data="state.treeData"
        :field-names="{ title: 'name', children: 'children', key: 'id' }"
        show-icon
        default-expand-all
        @select="(_, { node }) => folderClick(node)"
      >
      </a-tree>
    </div>

    <div class="px-4" :style="{ width: 'calc(100% - 340px)' }">
      <DynamicForm class="mt-4" :config="dyConfig" :questions="dyQuestions" />
      <DynamicTable :tables="dyTable" :config="dyTableConfig" :icons="dyIcons" ref="fileRef">
        <template #status="{ text, record, column }">
          <a-switch :checked="record.status" checked-children="开" un-checked-children="关" :checked-value="1" :un-checked-value="0" @change="(value) => statusChange(record, value)" />
        </template>
        <!-- 面包屑 -->
        <template v-if="state.level !== 0" #title>
          <div>
            <a-breadcrumb>
              <template v-for="(item, index) in breadcrumbs" :key="index">
                <a-breadcrumb-item :class="index === breadcrumbs.length - 1 ? null : 'hierarchy'" @click="folderClick(item)">{{ item.name }}</a-breadcrumb-item>
              </template>
            </a-breadcrumb>
          </div>
        </template>

        <!-- 文件夹图片和名称 -->
        <template #fileImg="{ record }">
          <img class="w-11.5 h-11.5 cursor-pointer" @click="folderClick(record)" src="@/assets/img/fileImg/fileFolder.png" alt="" />
        </template>
        <template #fileName="{ record }">
          <p class="text-4 text-black text-opacity-65 cursor-pointer">
            <span @click="folderClick(record)">{{ record.name }}</span>
          </p>
        </template>
      </DynamicTable>
    </div>

    <div v-if="state.showDetail">
      <ViewDialog v-model:visible="state.showDetail" :data="state.showData" :show-type="state.showType" :parentId="dyTableConfig.params.parentId" :detailId="state.detailId" @handleEdit="handleEdit" />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { DynamicForm, DynamicTable } from '@/components/public-template';
import { Api, deptBatchDelete, deptGetChildrenFolders, deptSave, deptUpdateStatus } from '@/config/api/deptFile';
import { DYNAMICLAYERCLEAR, LOCALSUBSERVE, RESETTABLE, UPLOADESERVE } from '@/mixins/subject/subject-types';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue/lib/icons';
import { Modal, message } from 'ant-design-vue';
import { filter } from 'rxjs/operators';
import { createVNode, getCurrentInstance, nextTick, onBeforeUnmount, onMounted, reactive, ref } from 'vue';
import ViewDialog from './components/viewDialog.vue';
import indexService from './index.service';
import { paramsData } from '@/components/public-template/publicMethod';

const { proxy }: any = getCurrentInstance();

const state = reactive({
  searchName: '',
  selectedKeys: [],
  treeData: [],
  showData: null,
  showDetail: false,
  showType: '',
  detailId: '',
  level: 0
});
const fileRef = ref(null);
const breadcrumbs: any = ref([]);
const dyQuestions: any = reactive(indexService.getQuestions());
const dyConfig: any = {
  labelCol: 4,
  wrapperCol: 18,
  grid: 8, // 分栏
  style: 'table-form',
  cancelSave: true // 隐藏底部按钮
};

const dyTable: any = reactive(indexService.getTables());
const dyIcons: any = reactive(indexService.getIcons());
const dyTableConfig: any = reactive({
  name: 'deptFile',
  queryUrl: Api.deptPage,
  protType: 'post',
  rowSelection: { type: 'checkbox' },
  scroll: {
    x: 2000
  },
  params: { parentId: '' },
  beforeWithMethod: (data) => {
    data.forEach((item) => {
      delete item.children;
    });
    return data;
  }
});

const subscribeSub = proxy.$NotificationFormSub
  .getParams()
  .pipe(filter((res) => res !== 0))
  .subscribe((item: any) => {
    if (item.key === LOCALSUBSERVE && item.state.name == dyTableConfig.name) {
      // 上方按钮-添加
      const params = { ...item.value, parentId: dyTableConfig.params.parentId };
      deptSave(params).then((result) => {
        if (result.success) {
          message.success(!item.value.id ? '添加成功' : '修改成功');
          getFolderTree();
          proxy.$NotificationPubSub.pushParams({ key: DYNAMICLAYERCLEAR, value: { name: 'form' } }); // 取消弹层
          proxy.$NotificationFormSub.pushParams({ key: RESETTABLE, value: { name: 'deptFile' } }); // 更新table
        }
      });
    } else if (item.key === UPLOADESERVE) {
      // 上方按钮-上传
      proxy.$NotificationFormSub.pushParams({ key: RESETTABLE, value: { name: 'deptFile' } }); // 更新table
    }
  });

// 监听table
const subscribeSubTab = proxy.$NotificationPubSub
  .getParams()
  .pipe(filter((res) => res !== 0))
  .subscribe((item: any) => {
    if (item.key === 'DYNAMICLOCALICONS' && item.value.value === '添加') {
      state.showType = 'ADD';
      state.showDetail = true;
    } else if (item.key === 'DYNAMICLOCALICONS' && item.value.value === '删除') {
      // 上方按钮-批量删除
      if (item.state.selected.length > 0) {
        Modal.confirm({
          title: '删除提示框',
          okText: '确认',
          cancelText: '取消',
          content: '是否确认删除所选内容？',
          onOk() {
            const parameterList = item.state.selected.map((reItem) => ({
              folder: reItem.folder,
              id: reItem.id,
              subsystem: 5
            }));
            deptBatchDelete({ parameterList }).then((res) => {
              if (res.success) {
                message.success('删除成功');
                getFolderTree();
                proxy.$NotificationFormSub.pushParams({ key: RESETTABLE, value: { name: 'deptFile' } }); // 更新table
              }
            });
          }
        });
      } else {
        message.warning('请先选中一个选项');
      }
    } else if (item.key === 'DYNAMICLOCALTABLE' && item.value.part.key === 'code') {
      state.showDetail = true;
      state.showType = 'VIEW';
      state.detailId = item.value.data.id;
    }
  });

onMounted(() => {
  getFolderTree();
});

onBeforeUnmount(() => {
  subscribeSub && subscribeSub.unsubscribe();
  proxy.$NotificationFormSub.clearParams();
  subscribeSubTab && subscribeSubTab.unsubscribe();
  proxy.$NotificationPubSub.clearParams();
});

// 获取项目文件目录
function getFolderTree() {
  const params = {
    name: state.searchName
  };
  deptGetChildrenFolders(params).then((result) => {
    if (result.success) {
      state.treeData = result.data;
    }
  });
}

// 更改状态时触发
const statusChange = (record, value) => {
  Modal.confirm({
    title: '提示',
    icon: createVNode(ExclamationCircleOutlined),
    okText: '确定',
    cancelText: '取消',
    content: '是否确定修改状态？',
    onOk() {
      const params = {
        id: record.id,
        status: value
      };
      deptUpdateStatus(params).then((result) => {
        if (result.success) {
          message.success('修改成功');
          fileRef.value.getData();
        }
      });
    }
  });
};

// 点击文件夹
function folderClick(node) {
  // 修改上传按钮传参
  for (let i = 0; i < dyIcons.length; i++) {
    if (dyIcons[i].key == 'upload') {
      dyIcons[i].state.params.directoryId = node.id;
      // dyIcons[i].hidden = !node.id;
      break;
    }
  }
  // table传参
  if (!node.level) node.level = 1;
  state.selectedKeys[0] = node.id;
  state.level = node.level;
  dyTableConfig.params.parentId = node.id;
  if (breadcrumbs.value.length === 0) {
    breadcrumbs.value.push({
      id: node.id,
      name: node.name
    });
    return;
  }
  let flag = true;
  breadcrumbs.value.forEach((item, index) => {
    if (item?.id === node.id) {
      breadcrumbs.value.splice(index + 1);
      flag = false;
    }
  });
  if (flag) {
    breadcrumbs.value.push({
      id: node.id,
      name: node.name
    });
  }
  fileRef.value.getData();
}

//面包屑
// function breadcrumb(arr: any, key: any, finalData: Array<any> = []) {
//   for (let i = 0, len = arr.length; i < len; i++) {
//     finalData.push({ name: arr[i].name, id: arr[i].id });
//     if (arr[i].id === key) {
//       return finalData;
//     } else if (arr[i].children && arr[i].children.length >= 1) {
//       if (breadcrumb(arr[i].children, key, finalData) != false) return finalData;
//     }
//     finalData.pop();
//   }
//   return false;
// }

// 目录编辑
function handleEdit(data) {
  state.showDetail = false;
  nextTick(() => {
    state.showType = 'EDIT';
    state.showDetail = true;
    state.showData = data;
  });
}
</script>

<style lang="less" scoped>
:deep(.tree-warpper) {
  .ant-tree-switcher {
    line-height: 36px;
  }

  .ant-tree-node-content-wrapper {
    min-height: 36px;
    line-height: 36px;

    &.ant-tree-node-selected {
      background-color: #e5eefd;
      color: #005aea;
    }
  }
}
.hierarchy {
  cursor: pointer;
}
.hierarchy:hover {
  color: #409eff;
}
</style>
